// ==UserScript==
// @name     红院安全学习考试助手
// @include  http://10.10.10.46/*
// @require  https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js
// @require  https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js
// @version  0.0.1
// @grant    none
// ==/UserScript==

// 答题速度
speed = 1000
// 是否自动点击提交
autocommit = true
// 服务器地址
axios.defaults.baseURL = "http://127.0.0.1:6500";
axios.defaults.headers.post['Content-Type'] = 'application/json';

/**
 * 答题
 */
function accurateSearch() {
  $("div.shiti").each(async (index, element) => {
    let subject = $(element).children("h3").html().match("\\d+、(.*)")[1]
    await axios.post("/api/secure/search", {subject: subject}).then((resp) => {
      let options = $(element).find("ul input");
      $(resp.data.content).each((i, e) => {
        $(options[e]).click();
      });
    });
  });
}

/**
 * 翻页
 */
function paging() {
  const page_info = $("#dati > div.nav").contents();
  let page = $(page_info[4]).text().trim();
  if (page === undefined || page === null || page.trim() === '') {
    // 考试页无跳转
    page = "共有100 题 第1 / 1 页  跳转到第";
  }

  const page_match = page.match("共有100 题 第(\\d+) / (\\d+) 页  跳转到第");
  const current_page = parseInt(page_match[1]);
  const sum_page = parseInt(page_match[2]);
  if (current_page < sum_page) {
    $("#dati > div.nav > input[type=button]:nth-child(2)").click();
  } else if (current_page === sum_page && autocommit) {
    $("#dati > div.nav > input[type=button][value='提交答卷']").click();
  }
}

$(function () {
  // 判断是否在考试页面
  if ($("#dati").length > 0) {
    accurateSearch();
    setTimeout(paging, speed);
  }
});
